/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hyce;

/**
* Simple modification of "FileEncrypor.java".  The
* previously encrypted "clear.txt.des" is read, decrypted
* and written back as "clear.txt.dcr"
*/

import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class FileDecryptor
{

    /**
     * Note: All kinds of exceptions can be thrown in main.
     * See the API documentation for each method used.
     */

    public static void decrypt(String file, String pass) throws Exception
    {

       // File and password for decryption.
       String filename = file;
       String password = pass;

       FileInputStream inFile = new FileInputStream(filename);
       FileOutputStream outFile = new FileOutputStream(filename.substring(0, filename.length()-3)
               + "dcr");

       PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
       SecretKeyFactory keyFactory =
           SecretKeyFactory.getInstance("PBEWithMD5AndDES");
       SecretKey passwordKey = keyFactory.generateSecret(keySpec);

       // Read in the previouly stored salt and set the iteration count.

       byte[] salt = new byte[8];
       inFile.read(salt);
       int iterations = 100;

       PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);

       // Create the cipher and initialize it for decryption.

       Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
       cipher.init(Cipher.DECRYPT_MODE, passwordKey, parameterSpec);


       byte[] input = new byte[64];
       int bytesRead;
       while ((bytesRead = inFile.read(input)) != -1)
       {
          byte[] output = cipher.update(input, 0, bytesRead);
          if (output != null)
             outFile.write(output);
       }

       byte[] output = cipher.doFinal();
       if (output != null)
          outFile.write(output);

       inFile.close();
       outFile.flush();
       outFile.close();
   }
}